Multer : Web multer

更新时间:
2024-05-15
下载文档

Multer : Web multer

multer is a middleware for handling multipart/form-data, which is primarily used for uploading files.

multer adds a body object and a file or files object to the request object. The body object contains the values of the text fields of the form, the file or files object contains the files uploaded via the form.

User can use the following code to import the multer module.

var multer = require('middleware').multer;

Support

The following shows multer module APIs available for each permissions.

 User ModePrivilege Mode
multer
multer.diskStorage
multer.memoryStorage
upload.single
upload.array
upload.fields
upload.none
upload.any

Multer Object

multer(opts)

  • opts {Object} The following are the options that can be passed to multer:
    • dest {String} or storage {Function} Where to store the files.
    • fileFilter {Function} Function to control which files are accepted.
    • limits {Object} Limits of the uploaded data.
    • preservePath {Boolean} Keep the full path of files instead of just the base name.

multer accepts an options object, the most basic of which is the dest property, which tells multer where to upload the files. In case you omit the options object, the files will be kept in memory and never written to disk.

By default, multer will rename the files so as to avoid naming conflicts. The renaming function can be customized according to your needs.

dest | storage

In an average WebApp, only dest might be required, and configured as shown in the following example.

var upload = multer({ dest: './uploads' });

If you want more control over your uploads, you'll want to use the storage option instead of dest. multer ships with storage engines DiskStorage and MemoryStorage; More engines are available from third parties.

limits

An object specifying the size limits of the following optional properties. The following integer values are available:

KeyDescriptionDefault
fieldNameSizeMax field name size100 bytes
fieldSizeMax field value size (in bytes)1MB
fieldsMax number of non-file fieldsInfinity
fileSizeFor multipart forms, the max file size (in bytes)Infinity
filesFor multipart forms, the max number of file fieldsInfinity
partsFor multipart forms, the max number of parts (fields + files)Infinity
headerPairsFor multipart forms, the max number of header key=>value pairs to parse2000

Specifying the limits can help protect your site against denial of service (DoS) attacks.

fileFilter

Set this to a function to control which files should be uploaded and which should be skipped. The function should look like this:

function fileFilter(req, file, cb) {
  // The function should call `cb` with a boolean
  // to indicate if the file should be accepted

  // To reject this file pass `false`, like so:
  cb(null, false);

  // To accept the file pass `true`, like so:
  cb(null, true);

  // You can always pass an error if something goes wrong:
  cb(new Error('I don\'t have a clue!'));
}

multer.diskStorage(opts)

  • opts {Object} Options as follow;
    • destination {String} Get destination path.
    • filename {Function} Get file name.

The disk storage engine gives you full control on storing files to disk.

There are two options available, destination and filename. They are both functions that determine where the file should be stored.

destination is used to determine within which folder the uploaded files should be stored.

filename is used to determine what the file should be named inside the folder. If no filename is given, each file will be given a random name that doesn't include any file extension.

Each function gets passed both the request (req) and some information about the file (file) to aid with the decision.

Note that req.body might not have been fully populated yet. It depends on the order that the client transmits fields and files to the server.

Example

var storage = multer.diskStorage({
  destination: '/tmp/my-uploads',
  filename: function (req, file, cb) {
    cb(null, file.fieldname + '-' + Date.now());
  }
});

var upload = multer({ storage: storage });

multer.memoryStorage()

The memory storage engine stores the files in memory as Buffer objects. It doesn't have any options.

When using memory storage, the file info will contain a field called buffer that contains the entire file.

Example

var storage = multer.memoryStorage();
var upload = multer({ storage: storage });

Upload Object

upload.single(fieldname)

  • fieldname {String} Field name.

Accept a single file with the name fieldname. The single file will be stored in req.file.

upload.array(fieldname[, maxCount])

  • fieldname {String} Field name.
  • maxCount {Integer} Fields max count.

Accept an array of files, all with the name fieldname. Optionally error out if more than maxCount files are uploaded. The array of files will be stored in req.files.

upload.fields(fields)

  • fields {Array} Should be an array of objects with name and optionally a maxCount.

Accept a mix of files, specified by fields. An object with arrays of files will be stored in req.files.

Example

[
  { name: 'avatar', maxCount: 1 },
  { name: 'gallery', maxCount: 8 }
]

upload.none()

Accept only text fields. If any file upload is made, error with code LIMIT_UNEXPECTED_FILE will be issued.

upload.any()

Accepts all files that comes over the wire. An array of files will be stored in req.files.

File Object

Each file contains the following information:

KeyDescriptionNote
fieldnameField name specified in the form
originalnameName of the file on the user's computer
encodingEncoding type of the file
mimetypeMime type of the file
sizeSize of the file in bytes
destinationThe folder to which the file has been savedDiskStorage
filenameThe name of the file within the destinationDiskStorage
pathThe full path to the uploaded fileDiskStorage
bufferA Buffer of the entire fileMemoryStorage

Error Handling

When encountering an error, multer will delegate the error to WebApp.

If you want to catch errors specifically from multer, you can call the middleware function by yourself. You can use the MulterError class that is attached to the multer object itself (e.g. err instanceof multer.MulterError).

Example

var multer = require('middleware').multer;
var upload = multer().single('avatar');

app.post('/profile', function (req, res) {
  upload(req, res, function (err) {
    if (err instanceof multer.MulterError) {
      // A multer error occurred when uploading.
    } else if (err) {
      // An unknown error occurred when uploading.
    }

    // Everything went fine.
  });
});

Example

Don't forget the enctype="multipart/form-data" in your form.

<form action="/profile" method="post" enctype="multipart/form-data">
  <input type="file" name="avatar" />
</form>

Basic usage example:

var socket = require('socket');
var WebApp = require('webapp');
var multer = require('middleware').multer;

var upload = multer({ dest: './uploads' });

// Create app.
var app = WebApp.create('app', 0, socket.sockaddr(socket.INADDR_ANY, 8000));

app.post('/profile', upload.single('avatar'), function (req, res, next) {
  // req.file is the `avatar` file
  // req.body will hold the text fields, if there were any
});

app.post('/photos', upload.array('photos', 12), function (req, res, next) {
  // req.files is array of `photos` files
  // req.body will contain the text fields, if there were any
});

var cpUpload = upload.fields([{ name: 'avatar', maxCount: 1 }, { name: 'gallery', maxCount: 8 }]);
app.post('/cool-profile', cpUpload, function (req, res, next) {
  // req.files is an object (String -> Array) where fieldname is the key, and the value is array of files
  //
  // e.g.
  // req.files['avatar'][0] -> File
  // req.files['gallery'] -> Array
  //
  // req.body will contain the text fields, if there were any
});

// Start app.
app.start();

// Event loop.
while (true) {
  iosched.poll(50);
}

In case you need to handle a text-only multipart form, you should use the .none() method:

app.post('/profile', upload.none(), function (req, res, next) {
  // req.body contains the text fields
});
文档内容是否对您有所帮助?
有帮助
没帮助